package com.it.emall.service.impl;

import com.it.emall.domain.NutritionInfo;
import com.it.emall.domain.Recipes;
import com.it.emall.mapper.NutritionMapper;
import com.it.emall.mapper.RecommendationsMapper;
import com.it.emall.service.NutritionInfoService;
import com.it.emall.service.RecommendationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NutritionInfoServiceImpl implements NutritionInfoService {


    @Autowired
    private NutritionMapper nutritionMapper;

    @Autowired
    private RecommendationsMapper recommendationsMapper;


    @Override
    public List<Recipes> generateRecipes(int userId, int calories, int protein, int fat, int carbohydrate) {
        System.out.println("【开始处理用户输入的营养数据】");
        System.out.println("用户ID：" + userId);
        System.out.println("卡路里：" + calories + "，蛋白质：" + protein + "，脂肪：" + fat + "，碳水化合物：" + carbohydrate);

        // 1️⃣ **检查用户是否输入了有效的数值**
        boolean isAllZero = (calories == 0 && protein == 0 && fat == 0 && carbohydrate == 0);
        if (isAllZero) {
            System.out.println("⚠️ 用户输入的营养信息全部为 0，返回所有食谱");
            return recommendationsMapper.findAllRecipes();
        }

        // 2️⃣ **动态构建 SQL 查询**
        List<Recipes> filteredRecipes = recommendationsMapper.findRecipesByDynamicNutrition(
                (calories > 0) ? calories : Integer.MAX_VALUE,
                (protein > 0) ? protein : Integer.MAX_VALUE,
                (fat > 0) ? fat : Integer.MAX_VALUE,
                (carbohydrate > 0) ? carbohydrate : Integer.MAX_VALUE
        );

        System.out.println("✅ 查询到符合用户需求的食谱数量: " + filteredRecipes.size());

        if (!filteredRecipes.isEmpty()) {
            // 3️⃣ **存储用户输入数据**
            NutritionInfo nutritionInfo = new NutritionInfo();
            nutritionInfo.setUserId(userId);
            nutritionInfo.setCalories(calories);
            nutritionInfo.setProtein(protein);
            nutritionInfo.setFat(fat);
            nutritionInfo.setCarbohydrate(carbohydrate);

            nutritionMapper.insertNutritionInfo(nutritionInfo);
            System.out.println("✅ 营养信息已存入数据库");
        } else {
            System.out.println("❌ 未找到符合条件的食谱，不存储营养信息");
        }

        return filteredRecipes;
    }
}
